package com.kla.power.util;


import com.alibaba.fastjson.JSONObject;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class JsonUtil {

    /**
     * JSON对象转成Java对象
     *
     * @param jsonObject
     * @return
     */
    public static <T> T jsonObjectToBean ( JSONObject jsonObject, Class<T> beanClass ) throws Exception {
        if ( jsonObject == null ) {
            throw new StateException ( StateEnum.ERROR, "json对象转Java对象，json对象为空，无法接受异常" );
        }
        Field[] fb = beanClass.getDeclaredFields ();
        T t = beanClass.newInstance ();
        for ( int j = 0; j < fb.length; j++ ) {
            String fieldName = fb[j].getName ();
            String fieldNameU = fieldName.substring ( 0, 1 ).toUpperCase () + fieldName.substring ( 1 );
            Method method = beanClass.getMethod ( "set" + fieldNameU, fb[j].getType () );
            method.invoke ( t, jsonObject.get ( fieldName ) );
        }
        return t;
    }

    /**
     * Java对象转成JSON对象
     *
     * @param object
     * @return
     */
    public static JSONObject beanToJsonObject ( Object object ) {
        JSONObject jsonObject = ( JSONObject ) JSONObject.toJSON ( object );
        return jsonObject;
    }

    /**
     * @return a
     * @Author Wuzh
     * @Description java对象转成成json字符串
     * @Date 10:52
     **/
    public static String beanToJsonString ( Object object ) {
        String string = JSONObject.toJSONString ( object );
        return string;
    }

    /**
     * @return a
     * @Author Wuzh
     * @Descriptio json字符串转成Java对象
     * @Date 10:56
     **/
    public static <T> T jsonStringToBean ( String jsonStr, Class<T> tClass ) {
        T object = JSONObject.parseObject ( jsonStr, tClass );
        return object;
    }

    /**
     * @Author Wuzh
     * @Descriptio JSON字符串转JSON对象
     * @Date 10:59
     **/
    public static JSONObject jsonStringToJson ( String jsonString ) {
        return JSONObject.parseObject ( jsonString );
    }
}
